const WebSocket = require('ws');

class Code1102Tester {
  constructor() {
    this.ws = null;
    this.token = null;
    this.testResults = [];
  }

  async connect () {
    return new Promise((resolve, reject) => {
      console.log('🔌 连接到WebSocket服务器...');

      this.ws = new WebSocket('ws://localhost:3000/user-service/websocket');

      this.ws.on('open', () => {
        console.log('✅ WebSocket连接成功');
        resolve();
      });

      this.ws.on('error', (error) => {
        console.error('❌ WebSocket连接失败:', error.message);
        reject(error);
      });
    });
  }

  async login () {
    return new Promise((resolve, reject) => {
      console.log('🔐 开始登录...');

      const loginData = {
        act_id: 1000,
        username: "testuser",
        password: "testpass"
      };

      this.ws.send(JSON.stringify(loginData));

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1000) {
            this.ws.removeListener('message', responseHandler);

            if (message.code === 0) {
              this.token = message.data.token;
              console.log('✅ 登录成功');
              resolve();
            } else {
              console.log('❌ 登录失败:', message.msg);
              reject(new Error(message.msg));
            }
          }
        } catch (error) {
          console.error('❌ 解析登录响应失败:', error);
          reject(error);
        }
      };

      this.ws.on('message', responseHandler);

      setTimeout(() => {
        this.ws.removeListener('message', responseHandler);
        reject(new Error('登录超时'));
      }, 10000);
    });
  }

  async testCode1102Pagination () {
    console.log('\n📄 测试1102指令分页查询...');

    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1102分页查询测试', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      // 设置响应监听器
      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1102) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            console.log('📊 1102响应数据:', JSON.stringify(message, null, 2));

            if (message.code === 0) {
              console.log('✅ 1102查询成功');

              // 验证分页信息
              const hasPage = 'page' in message;
              const hasSum = 'sum' in message;
              const hasList = 'list' in message;

              console.log(`📄 分页信息检查:`);
              console.log(`  - page字段: ${hasPage ? '✅' : '❌'} (值: ${message.page})`);
              console.log(`  - sum字段: ${hasSum ? '✅' : '❌'} (值: ${message.sum})`);
              console.log(`  - list字段: ${hasList ? '✅' : '❌'} (长度: ${message.list ? message.list.length : 0})`);

              if (hasPage && hasSum && hasList) {
                console.log('✅ 分页信息格式正确');
                this.addTestResult('1102分页查询测试', true, `页码: ${message.page}, 总数: ${message.sum}, 当前页数量: ${message.list.length}`);
              } else {
                console.log('❌ 分页信息格式不正确');
                this.addTestResult('1102分页查询测试', false, '缺少分页信息字段');
              }
            } else {
              console.log(`❌ 1102查询失败: ${message.msg || '未知错误'}`);
              this.addTestResult('1102分页查询测试', false, message.msg || '查询失败');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 解析1102响应失败:', error);
          this.addTestResult('1102分页查询测试', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      // 发送1102查询请求
      const requestData = {
        act_id: 1102,
        s: 1, // 1星副将
        t: 4, // 按攻击力排序
        pageNum: 0 // 第1页
      };

      console.log('📤 发送1102查询请求:', JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      // 设置超时
      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          console.log('⏰ 1102查询请求超时');
          this.addTestResult('1102分页查询测试', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  addTestResult (testName, success, message) {
    this.testResults.push({
      test: testName,
      success: success,
      message: message
    });
  }

  printTestResults () {
    console.log('\n📊 测试结果汇总:');
    console.log('='.repeat(50));

    this.testResults.forEach((result, index) => {
      const status = result.success ? '✅' : '❌';
      console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
    });

    const successCount = this.testResults.filter(r => r.success).length;
    const totalCount = this.testResults.length;

    console.log('='.repeat(50));
    console.log(`总计: ${successCount}/${totalCount} 个测试通过`);
  }

  async run () {
    try {
      await this.connect();
      // 跳过登录，直接测试1102指令
      await this.testCode1102Pagination();

      this.printTestResults();
    } catch (error) {
      console.error('❌ 测试执行失败:', error.message);
    } finally {
      if (this.ws) {
        this.ws.close();
        console.log('🔌 WebSocket连接已关闭');
      }
    }
  }
}

// 运行测试
const tester = new Code1102Tester();
tester.run();
